package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/4/11
 * \* Time: 8:45
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class TcpThreadEchoServer {
    private ServerSocket serverSocket = null;

    public TcpThreadEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            //由于TCP是有连接的，不能一上来就读数据，而是先建立连接
            //accept就是在接电话，接电话的前提是有人给你打，如果当前没有客户端尝试建立连接，此处的accept就会阻塞
            //accept返回一个socket对象，称为clientSocket，后续和客户端之间的沟通，都是通过clientSocket来完成
            //进一步说，serverSocket就干了一件事，接电话
            Socket clientSocket = serverSocket.accept();
            //改进方法：在这个地方，每次accept成功，都创建一个进程，由新线程负责执行这个processConnection方法
            Thread t = new Thread(()->{
                processConnection(clientSocket);
            });
            t.start();
        }
    }

    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s :%d] 客户端建立连接！\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //接下来处理请求和响应
        //这里针对TCP socket 的读写就和文件读写一模一样
        try(InputStream inputStream = clientSocket.getInputStream()){
            try(OutputStream outputStream = clientSocket.getOutputStream()){
                //循环的处理每个请求，分别返回响应
                Scanner scanner = new Scanner(inputStream);
                while (true){
                    //1.读取请求
                    if (!scanner.hasNext()){
                        System.out.printf("[%s: %d] 客户端断开连接！\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                        break;
                    }
                    //此处用Scanner更方便，如果不用Scanner就用原生的InputStream的read也是可以的
                    String request = scanner.next();
                    //2.根据请求，计算响应
                    String response = process(request);
                    //3.把这个响应返回给客户端
                    //为了方便起见，可以使用PrintWriter 把 OutputStream包裹一下
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.write(response);
                    //刷新缓冲区
                    printWriter.flush();

                    System.out.printf("[%s : %d] req:%s,resp:%s\n" ,clientSocket.getInetAddress().toString(),
                            clientSocket.getPort(),request,response);

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //此处记得来个关闭操作
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ;
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpThreadEchoServer server = new TcpThreadEchoServer(9090);
        server.start();
    }
}
